package ele_handler

import (
	"go-yuque/logger"
	"strconv"
)

const ulOlKey = "ul_ol"

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &ulStruct{}
			h.elements = []string{"ul"}
			return h
		},

		func() YuqueElementHandler {
			h := &olStruct{}
			h.elements = []string{"ol"}
			h.olIdx = 1
			return h
		})
}

type ulOlI interface {
	getIndent() int64
}

type ulStruct struct {
	BaseHandler
	indent int64 `name:"列表缩进"`
}

func (ul *ulStruct) getIndent() int64 {
	return ul.indent
}

func (ul *ulStruct) preHandle() error {

	if ul.ctxMap != nil {
		ulS, ulOk := (ul.ctxMap)[ulOlKey].([]ulOlI)
		if ulOk {
			ulS = append(ulS, ul)
			(ul.ctxMap)[ulOlKey] = ulS
		} else {
			ulS = []ulOlI{ul}
			(ul.ctxMap)[ulOlKey] = ulS
		}

		// 获取节点属性 data-lake-indent，有这个数据就要进行缩进
		if ul.node != nil {
			indentVal := findAttribute(ul.node, "data-lake-indent")
			ul.indent, _ = strconv.ParseInt(indentVal, 10, 64)
		}

		logger.Debugf("ctx pointer:%p, ul:%+v", ul.ctxMap, (ul.ctxMap)[ulOlKey])
	}

	return nil
}

func (ul *ulStruct) postHandle() error {
	// 删除 ul_ol 中最后的实例
	if ul.ctxMap != nil {
		ulS, ok := (ul.ctxMap)[ulOlKey].([]*ulOlI)
		if ok {
			ulS = ulS[:len(ulS)-1]
			(ul.ctxMap)[ulOlKey] = ulS
		}
	}

	return nil
}

// 有序列表
type olStruct struct {
	BaseHandler
	indent int64 `name:"列表缩进"`
	olIdx  int   `name:"有序列表序号"`
}

func (ol *olStruct) getIndent() int64 {
	return ol.indent
}

func (ol *olStruct) preHandle() error {
	// 放入 ctx
	if ol.ctxMap != nil {
		olS, olOk := (ol.ctxMap)[ulOlKey].([]ulOlI)
		if olOk {
			olS = append(olS, ol)
			(ol.ctxMap)[ulOlKey] = olS
		} else {
			olS = []ulOlI{ol}
			(ol.ctxMap)[ulOlKey] = olS
		}

		// 获取节点属性 data-lake-indent，有这个数据就要进行缩进
		if ol.node != nil {
			indentVal := findAttribute(ol.node, "data-lake-indent")
			ol.indent, _ = strconv.ParseInt(indentVal, 10, 64)
		}
		logger.Debugf("ctx pointer:%p, ol:%+v", ol.ctxMap, (ol.ctxMap)[ulOlKey])
	}

	return nil
}

func (ol *olStruct) postHandle() error {
	// 删除 ul_ol 中最后的实例
	if ol.ctxMap != nil {
		olS, olOk := (ol.ctxMap)[ulOlKey].([]ulOlI)
		if olOk {
			olS = olS[:len(olS)-1]
			(ol.ctxMap)[ulOlKey] = olS
		}
	}

	return nil
}
